package com.marion.mzuul.job;

import com.marion.mzuul.config.RedisConfig;
import lombok.extern.slf4j.Slf4j;
import org.redisson.api.RLock;
import org.redisson.api.RedissonClient;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.scheduling.annotation.EnableScheduling;
import org.springframework.scheduling.annotation.Scheduled;
import org.springframework.stereotype.Component;

@EnableScheduling
@Component
@Slf4j
public class ZuulJob {

    @Autowired
    private RedisConfig redisConfig;

    private static final String M_ID = java.util.UUID.randomUUID().toString();

    /**
     * 分布式定时任务
     * 检测订单过期
     */
    @Scheduled(initialDelay = 1000L, fixedDelay = 5000L)
    public void checkExpireOrder() {

        if (1 == 1) {
            return ;
        }

        /**
         * 1. 指定解锁时间，不会自动续期
         * 2. lock默认看门口解决死锁问题，30s自动续期，1/3自动续期
         * 3. 读写锁应用场景：修改数据，读等待修改完成显示
         */
        log.info("[checkExpireOrder] check start... {}", M_ID);
        RedissonClient redisson = redisConfig.redissonClt();
        RLock lock = redisson.getLock("order");

        lock.lock();

        try {
            // TODO: 2021/10/11 模拟业务操作
            Thread.sleep(5000L);
        } catch (InterruptedException e) {
            e.printStackTrace();
        } finally {
//            lock.unlock();
        }

//        boolean lk = lock.tryLock();
//        if (lk) {
//            log.info("[checkExpireOrder] lock success, {}", M_ID);
//            try {
//                // TODO: 2021/10/11 模拟业务操作
//                Thread.sleep(5000L);
//            } catch (InterruptedException e) {
//                e.printStackTrace();
//            } finally {
//                lock.unlock();
//            }
//        } else {
//            log.info("[checkExpireOrder] lock failed, {}", M_ID);
//        }
        log.info("[checkExpireOrder] check end... {}", M_ID);
    }

}
